package cn.qianxun.meta.dept.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.ObjectUtil;
import cn.qianxun.meta.common.core.dto.RowsData;
import cn.qianxun.meta.common.core.dto.component.model.dto.SelectDeptInfoParamDTO;
import cn.qianxun.meta.common.core.dto.component.model.vo.SelectAssetResultVO;
import cn.qianxun.meta.common.core.field.AbstractFieldAssert;
import cn.qianxun.meta.common.core.utils.BeanCopyUtils;
import cn.qianxun.meta.common.core.utils.StringUtils;
import cn.qianxun.meta.common.core.utils.TreeBuildUtils;
import cn.qianxun.meta.common.core.web.dto.SelectLongDTO;
import cn.qianxun.meta.common.core.web.dto.SelectStringDTO;
import cn.qianxun.meta.common.core.web.dto.SelectVO;
import cn.qianxun.meta.common.core.web.vo.RemoveLongDTO;
import cn.qianxun.meta.dept.dto.SysDeptAddDTO;
import cn.qianxun.meta.dept.dto.SysDeptQueryDTO;
import cn.qianxun.meta.dept.dto.SysDeptStatusDTO;
import cn.qianxun.meta.dept.entity.SysDept;
import cn.qianxun.meta.dept.mapper.SysDeptMapper;
import cn.qianxun.meta.dept.service.ISysDeptService;
import cn.qianxun.meta.dept.vo.SelectSysDeptResultVO;
import cn.qianxun.meta.dept.vo.SysDeptVO;
import cn.qianxun.meta.role.entity.SysRole;
import cn.qianxun.meta.role.mapper.SysRoleMapper;
import cn.qianxun.meta.user.dto.UserDeptRoleSelectDTO;
import cn.qianxun.meta.user.entity.SysUser;
import cn.qianxun.meta.user.mapper.SysUserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import cn.qianxun.meta.common.core.constant.CacheNames;
import cn.qianxun.meta.common.core.constant.Constants;
import cn.qianxun.meta.common.core.constant.UserConstants;
import cn.qianxun.meta.common.core.exception.ServiceException;
import cn.qianxun.meta.common.mybatis.helper.DataBaseHelper;
import cn.qianxun.meta.common.satoken.utils.LoginHelper;
import cn.qianxun.meta.common.security.resdata.SelectPageDTO;
import cn.qianxun.meta.dept.api.dto.ApiAddDeptDTO;
import cn.qianxun.meta.dept.api.dto.ApiEditDeptDTO;
import cn.qianxun.meta.dept.api.dto.ApiSysDeptQueryDTO;
import cn.qianxun.meta.dept.api.dto.SelectDeptInfoByNameDTO;
import cn.qianxun.meta.dept.api.vo.ApiDeptDetailsVO;
import cn.qianxun.meta.dept.api.vo.ApiSysDeptListVO;
import cn.qianxun.meta.redis.utils.CacheUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author fuzhilin
 * @since 2023-08-21 02:30:54
 */
@Service
@RequiredArgsConstructor
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements ISysDeptService {


    private final SysUserMapper userMapper;
    private final SysRoleMapper roleMapper;

    @Override
    public List<SysDeptVO> selectDeptList(SysDeptQueryDTO dept) {
        LambdaQueryWrapper<SysDept> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysDept::getDelFlag, Constants.STATUS_NORMAL).like(StringUtils.isNotBlank(dept.getDeptName()), SysDept::getDeptName, dept.getDeptName()).like(StringUtils.isNotBlank(dept.getShortName()), SysDept::getShortName, dept.getShortName()).like(StringUtils.isNotBlank(dept.getLeader()), SysDept::getLeader, dept.getLeader()).like(StringUtils.isNotBlank(dept.getPhone()), SysDept::getPhone, dept.getPhone()).like(StringUtils.isNotBlank(dept.getEmail()), SysDept::getEmail, dept.getEmail()).eq(StringUtils.isNotBlank(dept.getNature()), SysDept::getNature, dept.getNature()).eq(StringUtils.isNotBlank(dept.getStatus()), SysDept::getStatus, dept.getStatus()).eq(StringUtils.isNotBlank(dept.getAreaName()), SysDept::getAreaName, dept.getAreaName()).eq(StringUtils.isNotBlank(dept.getCityName()), SysDept::getCityName, dept.getCityName()).eq(StringUtils.isNotBlank(dept.getProvinceName()), SysDept::getProvinceName, dept.getProvinceName()).eq(StringUtils.isNotBlank(dept.getStandardIndustry()), SysDept::getStandardIndustry, dept.getStandardIndustry()).eq(ObjectUtil.isNotEmpty(dept.getDeptType()), SysDept::getDeptType, dept.getDeptType()).eq(ObjectUtil.isNotEmpty(dept.getRegionLevel()), SysDept::getRegionLevel, dept.getRegionLevel()).eq(ObjectUtil.isNotEmpty(dept.getDeptFlag()), SysDept::getDeptFlag, dept.getDeptFlag()).eq(ObjectUtil.isNotEmpty(dept.getDeptId()), SysDept::getDeptId, dept.getDeptId()).orderByAsc(SysDept::getParentId).orderByAsc(SysDept::getOrderNum);
        return baseMapper.selectDeptList(lqw);
    }

    @Override
    public List<SysDeptVO> excludeChild(SelectLongDTO selectLongDTO) {
        LambdaQueryWrapper<SysDept> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysDept::getDelFlag, Constants.STATUS_NORMAL).eq(ObjectUtil.isNotNull(selectLongDTO.getIdLong()), SysDept::getDeptId, selectLongDTO.getIdLong()).orderByAsc(SysDept::getParentId).orderByAsc(SysDept::getOrderNum);
        return baseMapper.selectDeptList(lqw);
    }

    @Override
    public void checkDeptDataScope(Long idLong) {
        if (!LoginHelper.isAdmin()) {
            SysDeptQueryDTO dept = new SysDeptQueryDTO();
            dept.setDeptId(idLong);
            List<SysDeptVO> depts = this.selectDeptList(dept);
            if (CollUtil.isEmpty(depts)) {
                throw new ServiceException("没有权限访问部门数据！");
            }
        }
    }

    @Override
    public SysDeptVO selectDeptById(Long deptId) {
        SysDept dept = baseMapper.selectById(deptId);
        if (ObjectUtil.isNull(dept)) {
            return null;
        }
        SysDept parentDept = baseMapper.selectOne(new LambdaQueryWrapper<SysDept>().select(SysDept::getDeptName).eq(SysDept::getDeptId, dept.getParentId()));
        dept.setParentName(ObjectUtil.isNotNull(parentDept) ? parentDept.getDeptName() : null);
        SysDeptVO sysDeptVO = new SysDeptVO();
        BeanCopyUtils.copy(dept, sysDeptVO);
        return sysDeptVO;
    }

    @Override
    public boolean checkDeptNameUnique(SysDeptAddDTO dept) {
        boolean exist = baseMapper.exists(new LambdaQueryWrapper<SysDept>().eq(SysDept::getDeptName, dept.getDeptName()).eq(SysDept::getParentId, dept.getParentId()).ne(ObjectUtil.isNotNull(dept.getDeptId()), SysDept::getDeptId, dept.getDeptId()));
        return !exist;
    }

    @Override
    public Boolean insertDept(SysDeptAddDTO sysDeptAddDTO) {
        if (StringUtils.isNotNull(sysDeptAddDTO.getParentId())) {
            SysDept info = baseMapper.selectById(sysDeptAddDTO.getParentId());
            // 如果父节点不为正常状态,则不允许新增子节点
            if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
                throw new ServiceException("部门停用，不允许新增");
            }
            sysDeptAddDTO.setAncestors(info.getAncestors() + StringUtils.SEPARATOR + sysDeptAddDTO.getParentId());
        } else {
            sysDeptAddDTO.setAncestors("0");
        }
        SysDept dept = new SysDept();
        BeanCopyUtils.copy(sysDeptAddDTO, dept);
        dept.setCreateBy(LoginHelper.getUserName());
        dept.setCreateTime(new Date());
        int insertNum = baseMapper.insert(dept);
        if (insertNum > 0) {
            return true;
        }
        return false;
    }

    @Override
    public long selectNormalChildrenDeptById(Long deptId) {
        return baseMapper.selectCount(new LambdaQueryWrapper<SysDept>().eq(SysDept::getStatus, UserConstants.DEPT_NORMAL).apply(DataBaseHelper.findInSet(deptId, "ancestors")));
    }

    @Override
    public Boolean updateDept(SysDeptAddDTO sysDeptAddDTO) {
        SysDept dept = new SysDept();
        BeanCopyUtils.copy(sysDeptAddDTO, dept);
        if (StringUtils.isNotNull(sysDeptAddDTO.getParentId())) {
            SysDept oldDept = baseMapper.selectById(dept.getDeptId());
            SysDept newParentDept = baseMapper.selectById(dept.getParentId());
            if (ObjectUtil.isNotNull(newParentDept) && ObjectUtil.isNotNull(oldDept)) {
                String newAncestors = newParentDept.getAncestors() + StringUtils.SEPARATOR + newParentDept.getDeptId();
                String oldAncestors = oldDept.getAncestors();
                dept.setAncestors(newAncestors);
                updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
            }
        }
        dept.setUpdateBy(LoginHelper.getUserName());
        dept.setUpdateTime(new Date());
        int result = baseMapper.updateById(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors()) && !StringUtils.equals(UserConstants.DEPT_NORMAL, dept.getAncestors())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        if (result > 0) {
            return true;
        }
        return false;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(SysDept dept) {
        String ancestors = dept.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        baseMapper.update(null, new LambdaUpdateWrapper<SysDept>().set(SysDept::getStatus, UserConstants.DEPT_NORMAL).in(SysDept::getDeptId, Arrays.asList(deptIds)));
    }

    /**
     * 修改子元素关系
     *
     * @param deptId       被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
        List<SysDept> children = baseMapper.selectList(new LambdaQueryWrapper<SysDept>().apply(DataBaseHelper.findInSet(deptId, "ancestors")));
        List<SysDept> list = new ArrayList<>();
        for (SysDept child : children) {
            SysDept dept = new SysDept();
            dept.setDeptId(child.getDeptId());
            dept.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
            list.add(dept);
        }
        if (list.size() > 0) {
            if (baseMapper.updateBatchById(list)) {
                list.forEach(dept -> CacheUtils.evict(CacheNames.SYS_DEPT, dept.getDeptId()));
            }
        }
    }

    @Override
    public boolean hasChildByDeptId(Long deptId) {
        return baseMapper.exists(new LambdaQueryWrapper<SysDept>().eq(SysDept::getParentId, deptId));
    }

    @Override
    public boolean checkDeptExistUser(Long deptId) {
        return userMapper.exists(new LambdaQueryWrapper<SysUser>().eq(SysUser::getDeptId, deptId));
    }

    @Override
    public Boolean deleteDeptById(Long deptId) {
        int num = baseMapper.deleteById(deptId);
        if (num > 0) {
            return true;
        }
        return false;
    }

    @Override
    public List<Long> selectDeptListByRoleId(Long roleId) {
        SysRole role = roleMapper.selectById(roleId);
        return baseMapper.selectDeptListByRoleId(roleId, role.getDeptCheckStrictly());
    }

    @Override
    public List<Tree<Long>> selectDeptTreeList(SysDept dept) {
        SysDeptQueryDTO deptQueryDTO = new SysDeptQueryDTO();
        BeanCopyUtils.copy(dept, deptQueryDTO);
        List<SysDeptVO> depts = this.selectDeptList(deptQueryDTO);
        List<SysDept> sysDepts = BeanUtil.copyToList(depts, SysDept.class);
        return buildDeptTreeSelect(sysDepts);
    }

    @Override
    public RowsData<SelectVO> getDeptList(SelectPageDTO dto) {
        LambdaQueryWrapper<SysDept> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(dto.getField())) {
            wrapper.like(SysDept::getDeptName, dto.getField());
        }
        wrapper.eq(SysDept::getDelFlag, String.valueOf(Constants.ZERO));
        wrapper.eq(SysDept::getDeptFlag, Constants.ONE);
        Page<Object> page = PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<SysDept> deptList = baseMapper.selectList(wrapper);
        List<SelectVO> list = deptList.stream().map(sysDept -> {
            SelectVO vo = new SelectVO();
            vo.setLabel(sysDept.getDeptName());
            vo.setValue(String.valueOf(sysDept.getDeptId()));
            return vo;
        }).collect(Collectors.toList());
        return new RowsData<SelectVO>(list, page.getTotal(), page.getPageNum());
    }

    @Override
    public RowsData<SelectVO> operateSubList(SelectPageDTO dto) {
        LambdaQueryWrapper<SysDept> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(dto.getField())) {
            wrapper.like(SysDept::getDeptName, dto.getField());
        }
        wrapper.eq(SysDept::getDelFlag, String.valueOf(Constants.ZERO));
        wrapper.eq(SysDept::getDeptFlag, Constants.TOW);
        Page<Object> page = PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<SysDept> deptList = baseMapper.selectList(wrapper);
        List<SelectVO> list = deptList.stream().map(sysDept -> {
            SelectVO vo = new SelectVO();
            vo.setLabel(sysDept.getDeptName());
            vo.setValue(String.valueOf(sysDept.getDeptId()));
            return vo;
        }).collect(Collectors.toList());
        return new RowsData<SelectVO>(list, page.getTotal(), page.getPageNum());
    }

    @Override
    public SelectVO getDeptLeaderInfo(SelectStringDTO dto) {
        if (StringUtils.isNotNull(dto.getIdStr())) {
            SysDept sysDept = baseMapper.selectById(Long.valueOf(dto.getIdStr()));
            SelectVO vo = new SelectVO();
            vo.setLabel(sysDept.getLeader());
            vo.setValue(sysDept.getPhone());
            return vo;
        }
        return new SelectVO();
    }

    @Override
    public RowsData<SelectVO> useSubList(SelectPageDTO dto) {
        LambdaQueryWrapper<SysDept> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(dto.getField())) {
            wrapper.like(SysDept::getDeptName, dto.getField());
        }
        wrapper.eq(SysDept::getDelFlag, String.valueOf(Constants.ZERO));
        wrapper.eq(SysDept::getDeptFlag, Constants.THREE);
        Page<Object> page = PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<SysDept> deptList = baseMapper.selectList(wrapper);
        List<SelectVO> list = deptList.stream().map(sysDept -> {
            SelectVO vo = new SelectVO();
            vo.setLabel(sysDept.getDeptName());
            vo.setValue(String.valueOf(sysDept.getDeptId()));
            return vo;
        }).collect(Collectors.toList());
        return new RowsData<SelectVO>(list, page.getTotal(), page.getPageNum());
    }

    @Override
    public RowsData<ApiSysDeptListVO> deptList(ApiSysDeptQueryDTO dto) {
        LambdaQueryWrapper<SysDept> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysDept::getDelFlag, Constants.STATUS_NORMAL).like(StringUtils.isNotBlank(dto.getDeptName()), SysDept::getDeptName, dto.getDeptName()).like(StringUtils.isNotBlank(dto.getShortName()), SysDept::getShortName, dto.getShortName()).like(StringUtils.isNotBlank(dto.getLeader()), SysDept::getLeader, dto.getLeader()).like(StringUtils.isNotBlank(dto.getPhone()), SysDept::getPhone, dto.getPhone()).like(StringUtils.isNotBlank(dto.getEmail()), SysDept::getEmail, dto.getEmail()).eq(StringUtils.isNotBlank(dto.getNature()), SysDept::getNature, dto.getNature()).eq(StringUtils.isNotBlank(dto.getStatus()), SysDept::getStatus, dto.getStatus()).eq(StringUtils.isNotBlank(dto.getAreaName()), SysDept::getAreaName, dto.getAreaName()).eq(StringUtils.isNotBlank(dto.getCityName()), SysDept::getCityName, dto.getCityName()).eq(StringUtils.isNotBlank(dto.getProvinceName()), SysDept::getProvinceName, dto.getProvinceName()).eq(StringUtils.isNotBlank(dto.getStandardIndustry()), SysDept::getStandardIndustry, dto.getStandardIndustry()).eq(ObjectUtil.isNotEmpty(dto.getDeptType()), SysDept::getDeptType, dto.getDeptType()).eq(ObjectUtil.isNotEmpty(dto.getRegionLevel()), SysDept::getRegionLevel, dto.getRegionLevel()).eq(ObjectUtil.isNotEmpty(dto.getDeptFlag()), SysDept::getDeptFlag, dto.getDeptFlag()).orderByAsc(SysDept::getParentId).orderByAsc(SysDept::getOrderNum);
        Page<Object> page = PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<SysDept> deptList = baseMapper.selectList(lqw);
        List<ApiSysDeptListVO> list = deptList.stream().map(dept -> {
            ApiSysDeptListVO vo = new ApiSysDeptListVO();
            BeanUtils.copyProperties(dept, vo);
            return vo;
        }).collect(Collectors.toList());
        return new RowsData<ApiSysDeptListVO>(list, page.getTotal(), page.getPageNum());
    }

    @Override
    public void addDept(ApiAddDeptDTO dto) {
        SysDeptAddDTO sysDeptAddDTO = new SysDeptAddDTO();
        BeanUtils.copyProperties(dto, sysDeptAddDTO);
        if (!checkDeptNameUnique(sysDeptAddDTO)) {
            throw new ServiceException("新增部门'" + sysDeptAddDTO.getDeptName() + "'失败，部门名称已存在");
        }
        if (StringUtils.isNull(dto.getParentId())) {
            dto.setParentId(0L);
        }
        SysDept info = baseMapper.selectById(dto.getParentId());
        SysDept dept = new SysDept();
        // 如果父节点不为正常状态,则不允许新增子节点
        if (StringUtils.isNotNull(info)) {
            if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
                throw new ServiceException("部门停用，不允许新增");
            }
            dept.setAncestors(info.getAncestors() + StringUtils.SEPARATOR + dto.getParentId());
        }
        BeanCopyUtils.copy(dto, dept);
        baseMapper.insert(dept);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDept(RemoveLongDTO dto) {
        AbstractFieldAssert.isNull(dto.getRemoveIdList(), "id不能为空");
        List<SysDept> sysDeptList = baseMapper.selectVoBatchIds(dto.getRemoveIdList());
        for (SysDept sysDept : sysDeptList) {
            sysDept.setDelFlag(Constants.TOW);
        }
        if (!CollectionUtils.isEmpty(sysDeptList)) {
            this.updateBatchById(sysDeptList);
        }
    }

    @Override
    public ApiDeptDetailsVO deptDetails(Long id) {
        AbstractFieldAssert.isNull(id, "id不能为空");
        SysDept sysDept = baseMapper.selectById(id);
        if (StringUtils.isNull(sysDept)) {
            throw new ServiceException("该单位不存在");
        }
        ApiDeptDetailsVO vo = new ApiDeptDetailsVO();
        BeanUtils.copyProperties(sysDept, vo);
        return vo;
    }

    @Override
    public void editDept(ApiEditDeptDTO dto) {
        AbstractFieldAssert.isNull(dto.getId(), "id不能为空");
        SysDept sysDept = baseMapper.selectById(dto.getId());
        if (StringUtils.isNull(sysDept)) {
            throw new ServiceException("该单位不存在");
        }
        SysDeptAddDTO sysDeptAddDTO = new SysDeptAddDTO();
        BeanUtils.copyProperties(dto, sysDeptAddDTO);
        if (!checkDeptNameUnique(sysDeptAddDTO)) {
            throw new ServiceException("新增部门'" + sysDeptAddDTO.getDeptName() + "'失败，部门名称已存在");
        }
        if (StringUtils.isNull(dto.getParentId())) {
            dto.setParentId(0L);
        }

        SysDept info = baseMapper.selectById(dto.getParentId());
        if (StringUtils.isNotNull(info)) {
            // 如果父节点不为正常状态,则不允许新增子节点
            if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
                throw new ServiceException("部门停用，不允许新增");
            }
        }
        BeanUtils.copyProperties(dto, sysDept);
        baseMapper.updateById(sysDept);
    }

    @Override
    public RowsData<SelectVO> getProcessDeptPageList(UserDeptRoleSelectDTO dto) {
        LambdaQueryWrapper<SysDept> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(dto.getField())) {
            wrapper.like(SysDept::getDeptName, dto.getField());
        }
        wrapper.eq(SysDept::getDelFlag, Constants.ZERO);
        wrapper.orderByDesc(SysDept::getCreateTime);
        com.github.pagehelper.Page<Object> page = PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<SysDept> sysDeptList = baseMapper.selectList(wrapper);
        List<SelectVO> list = sysDeptList.stream().map(dept -> {
            SelectVO vo = new SelectVO();
            vo.setValue(String.valueOf(dept.getDeptId()));
            vo.setLabel(dept.getDeptName());
            return vo;
        }).collect(Collectors.toList());
        return new RowsData<>(list, page.getTotal(), dto.getPageNum());
    }

    @Override
    public void status(SysDeptStatusDTO dto) {
        AbstractFieldAssert.isNull(dto.getId(), "单位id不能为空");
        AbstractFieldAssert.isBlank(dto.getStatus(), "状态不能为空");
        SysDept sysDept = baseMapper.selectById(dto.getId());
        if (StringUtils.isNotNull(sysDept)) {
            sysDept.setStatus(dto.getStatus());
            baseMapper.updateById(sysDept);
        }
    }

    @Override
    public SelectAssetResultVO selectDeptInfoByParam(SelectDeptInfoParamDTO dto) {
        SelectAssetResultVO resultVO = new SelectAssetResultVO();
        resultVO.setAssetType(dto.getResultField());
        List<SelectSysDeptResultVO> deptList = new ArrayList<>();
        //判断是否是首节点 如果是首节点 资产集合为空 如果不是首节点(判断资产集合是否为空 如果为空则直接停止流程)
        List<SelectAssetResultVO.AssetListDTO> list = new ArrayList<>();
        if (Constants.ONE.equals(dto.getNode())) {
            dto.setAssets(null);
            deptList = baseMapper.selectDeptInfoByParam(dto);
        } else {
            //判断资产列表是否为空
            if (CollectionUtils.isEmpty(dto.getAssets()) || !Constants.DEPT.equals(dto.getLastResultField())) {
                return new SelectAssetResultVO();
            }
            deptList = baseMapper.selectDeptInfoByParam(dto);
        }
        //判断需要查询什么字段
        if (Constants.DEPT.equals(dto.getResultField())) {
            //建设单位
            List<String> constructNameList = deptList.stream().filter(o -> Constants.ONE.equals(o.getDeptFlag())).map(SelectSysDeptResultVO::getDeptName).filter(StringUtils::isNotEmpty).distinct().collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(constructNameList)) {
                SelectAssetResultVO.AssetListDTO constructVO = new SelectAssetResultVO.AssetListDTO();
                constructVO.setAsset(constructNameList);
                constructVO.setDeptFlag(Constants.ONE);
                list.add(constructVO);
            }
            //运维单位
            List<String> operationNameList = deptList.stream().filter(o -> Constants.TOW.equals(o.getDeptFlag())).map(SelectSysDeptResultVO::getDeptName).filter(StringUtils::isNotEmpty).distinct().collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(operationNameList)) {
                SelectAssetResultVO.AssetListDTO operationVO = new SelectAssetResultVO.AssetListDTO();
                operationVO.setAsset(operationNameList);
                operationVO.setDeptFlag(Constants.ONE);
                list.add(operationVO);
            }
            //使用单位
            List<String> useNameList = deptList.stream().filter(o -> Constants.THREE.equals(o.getDeptFlag())).map(SelectSysDeptResultVO::getDeptName).filter(StringUtils::isNotEmpty).distinct().collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(useNameList)) {
                SelectAssetResultVO.AssetListDTO useVO = new SelectAssetResultVO.AssetListDTO();
                useVO.setAsset(useNameList);
                useVO.setDeptFlag(Constants.THREE);
                list.add(useVO);
            }
        }
        resultVO.setAssetListList(list);
        return resultVO;
    }

    @Override
    public Map<String, Long> selectDeptInfoByName(SelectDeptInfoByNameDTO dto) {
        Map<String, Long> map = new HashMap<>();
        if (!CollectionUtils.isEmpty(dto.getDeptList())) {
            List<SysDept> sysDeptList = new ArrayList<>();
            List<String> deptNames = new ArrayList<>();
            for (SelectDeptInfoByNameDTO.DeptList dept : dto.getDeptList()) {
                for (String deptName : dept.getDeptNames()) {
                    Long count = baseMapper.selectCount(new LambdaQueryWrapper<SysDept>().eq(SysDept::getDeptName, deptName).eq(SysDept::getDelFlag, Constants.ZERO));
                    if (count < 1) {
                        SysDept sysDept = new SysDept();
                        sysDept.setDeptName(deptName);
                        sysDept.setDeptFlag(dept.getDeptFlag());
                        sysDept.setCreateTime(new Date());
                        sysDept.setUpdateTime(new Date());
                        sysDept.setParentId(0L);
                        sysDeptList.add(sysDept);
                    }
                }
                deptNames.addAll(dept.getDeptNames());
            }
            //保存单位表里没有的单位
            if (!CollectionUtils.isEmpty(sysDeptList)) {
                baseMapper.insertBatch(sysDeptList);
            }
            List<SysDept> deptList = baseMapper.selectList(new LambdaQueryWrapper<SysDept>().eq(SysDept::getDelFlag, Constants.ZERO).in(SysDept::getDeptName, deptNames));
            for (SysDept dept : deptList) {
                map.put(dept.getDeptName(), dept.getDeptId());
            }
        }
        return map;
    }

    @Override
    public List<SelectVO> getProcessDeptList(UserDeptRoleSelectDTO dto) {
        LambdaQueryWrapper<SysDept> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(dto.getField())) {
            wrapper.like(SysDept::getDeptName, dto.getField());
        }
        wrapper.eq(SysDept::getDelFlag, Constants.ZERO);
        wrapper.orderByDesc(SysDept::getCreateTime);
        List<SysDept> sysDeptList = baseMapper.selectList(wrapper);
        return sysDeptList.stream().map(dept -> {
            SelectVO vo = new SelectVO();
            vo.setValue(String.valueOf(dept.getDeptId()));
            vo.setLabel(dept.getDeptName());
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    public List<Tree<Long>> buildDeptTreeSelect(List<SysDept> depts) {
        if (CollUtil.isEmpty(depts)) {
            return CollUtil.newArrayList();
        }
        return TreeBuildUtils.build(depts, (dept, tree) -> tree.setId(dept.getDeptId()).setParentId(dept.getParentId()).setName(dept.getDeptName()).setWeight(dept.getOrderNum()));
    }

}
